﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;

namespace PDF_Generator
{
    public partial class MainForm : Form
    {
        DataBridge mDataBridge = null;

        public MainForm()
        {
            InitializeComponent();
            mDataBridge = new DataBridge();
        }
        
        private int GetTextAlign(string alignhID)
        {
            int resultAlign = 0;

            switch (alignhID)
            {
                case "ALIGN_CENTER":
                    resultAlign = iTextSharp.text.Element.ALIGN_CENTER;
                    break;

                case "ALIGN_LEFT":
                    resultAlign = iTextSharp.text.Element.ALIGN_LEFT;
                    break;

                case "ALIGN_RIGHT":
                    resultAlign = iTextSharp.text.Element.ALIGN_RIGHT;
                    break;

                case "ALIGN_TOP":
                    resultAlign = iTextSharp.text.Element.ALIGN_TOP;
                    break;

                case "ALIGN_BOTTOM":
                    resultAlign = iTextSharp.text.Element.ALIGN_BOTTOM;
                    break;

                case "ALIGN_MIDDLE":
                    resultAlign = iTextSharp.text.Element.ALIGN_MIDDLE;
                    break;

                case "ALIGN_BASELINE":
                    resultAlign = iTextSharp.text.Element.ALIGN_BASELINE;
                    break;

                case "ALIGN_UNDEFINED":
                    resultAlign = iTextSharp.text.Element.ALIGN_UNDEFINED;
                    break;

                default:
                    resultAlign = iTextSharp.text.Element.ALIGN_CENTER;
                    break;
            }

            return resultAlign;
        }

       private int ReturnFontStyle(string input_Style)
       {
           int result = 0;

           switch (input_Style)
           {
               case "NORMAL":
                   result = 0;
                   break;

               default :
                   break;
           }


           return result;
       }

       private DataTable GetPDFConfigTable(int tableID)
       {
            DataTable classifierTypesByIDList = new DataTable();

            try
            {
                if (mDataBridge.Connect() == true)
                {
                    string commandText = @"SELECT "
                                            + " TableID "
                                            + " , Row "
                                            + " , RowSpan "
                                            + " , [Column] "
                                            + " , ColSpan "
                                            + " , ContentType "
                                            + " , ContentText "
                                            + " , TextFont "
                                            + " , FontSize "
                                            + " , TextAlign "
                                            + " , BorderColor "
                                            + " , BackGroundColor "
                                            + " , FontEncoding "
                                            + " , FontStyle "
                                            + " , FontColor "
                                            + " , TextRotation "

                                            + " , (Select Name From Classifiers Where Code = ContentType) as \"Content Type\" "
                                            + " , (Select Name From Classifiers Where Code = BorderColor) as \"Border Color\" "
                                            + " , (Select Name From Classifiers Where Code = BackGroundColor) as \"BackGround Color\" "
                                            + " , (Select Name From Classifiers Where Code = TextFont) as \"Font Name\" "
                                            + " , (Select Name From Classifiers Where Code = TextAlign) as \"Text Align\" "
                                            + " , (Select Name From Classifiers Where Code = FontEncoding) as \"Font Encoding\" "
                                            + " , (Select Name From Classifiers Where Code = FontEncoding) as \"Font Style\" "
                                            + " , (Select Name From Classifiers Where Code = FontColor) as \"Font Color\" "

                                            + " FROM PDFConfig"
                                            + " WHERE PDFConfig.TableID = " + tableID;

                    classifierTypesByIDList = mDataBridge.ExecuteQuery(commandText);
                    //mLastError = mDataBridge.LastError;
                }
            }
            finally
            {
                mDataBridge.Disconnect();
            }

            return classifierTypesByIDList;
        }

        private DataTable GetPDFDataTable()
        {
            DataTable classifierTypesByIDList = new DataTable();

            try
            {
                if (mDataBridge.Connect() == true)
                {

                    string commandText = @"SELECT * FROM PDFData";
                    classifierTypesByIDList = mDataBridge.ExecuteQuery(commandText);
                    //mLastError = mDataBridge.LastError;
                }
            }
            finally
            {
                mDataBridge.Disconnect();
            }

            return classifierTypesByIDList;
        }
        
        private void configButton_Click(object sender, EventArgs e)
        {
            configDataGridView.DataSource = null;
            configDataGridView.DataSource = GetPDFConfigTable(0);
        }

        private void dataButton_Click(object sender, EventArgs e)
        {
            configDataGridView.DataSource = null;
            configDataGridView.DataSource = GetPDFDataTable();
        }

        private iTextSharp.text.BaseColor GetCellBorderOrBackGroundColor(string colorID)
        {
            iTextSharp.text.BaseColor resutColor = iTextSharp.text.BaseColor.WHITE;

            switch (colorID)
            {
                case "BLACK":
                    resutColor = iTextSharp.text.BaseColor.BLACK;
                    break;

                case "BLUE":
                    resutColor = iTextSharp.text.BaseColor.BLUE;
                    break;

                case "CYAN":
                    resutColor = iTextSharp.text.BaseColor.CYAN;
                    break;

                case "DARK_GRAY":
                    resutColor = iTextSharp.text.BaseColor.DARK_GRAY;
                    break;

                case "GRAY":
                    resutColor = iTextSharp.text.BaseColor.GRAY;
                    break;

                case "GREEN":
                    resutColor = iTextSharp.text.BaseColor.GREEN;
                    break;

                case "LIGHT_GRAY":
                    resutColor = iTextSharp.text.BaseColor.LIGHT_GRAY;
                    break;

                case "MAGENTA":
                    resutColor = iTextSharp.text.BaseColor.MAGENTA;
                    break;

                case "ORANGE":
                    resutColor = iTextSharp.text.BaseColor.ORANGE;
                    break;

                case "PINK":
                    resutColor = iTextSharp.text.BaseColor.PINK;
                    break;

                case "RED":
                    resutColor = iTextSharp.text.BaseColor.RED;
                    break;

                case "WHITE":
                    resutColor = iTextSharp.text.BaseColor.WHITE;
                    break;

                case "YELLOW":
                    resutColor = iTextSharp.text.BaseColor.YELLOW;
                    break;                    

                default:
                    break;            
            }

            return resutColor;
        }

        private int GetTableColumnsCount(int TableID)
        {
            int result = 0;

            try
            {
                if (mDataBridge.Connect() == true)
                {
                    string commandText = @"SELECT Max([Column])  FROM PDFConfig WHERE TableID = " + TableID + "";
                    DataTable maxColTable = mDataBridge.ExecuteQuery(commandText);

                    if (maxColTable != null && maxColTable.Rows.Count == 1 && !maxColTable.Rows[0][0].ToString().Equals(string.Empty))
                    {
                        commandText = @"SELECT Max(ColSpan) FROM PDFConfig WHERE TableID = " + TableID + " AND [Column]= " + maxColTable.Rows[0][0].ToString();
                        DataTable maxColSpanTable = mDataBridge.ExecuteQuery(commandText);

                        if (maxColSpanTable != null && maxColSpanTable.Rows.Count == 1 && !maxColSpanTable.Rows[0][0].ToString().Equals(string.Empty))
                        {
                            int maxColumn = (int)maxColTable.Rows[0][0];
                            int ColSpanOfmAXcOL = (int)maxColSpanTable.Rows[0][0];
                            result = maxColumn + ColSpanOfmAXcOL - 1;
                        }               
                    }
                }
            }
            finally
            {
                mDataBridge.Disconnect();
            }

            return result;
        }

        private PdfPTable CreatePdfPTable(int TableID)
        {
            int columnsCount = GetTableColumnsCount(TableID);

            PdfPTable resultTable = new PdfPTable(columnsCount);
            resultTable.WidthPercentage = 100;

            DataTable PDFTableConfig = GetPDFConfigTable(TableID);

            for (int i = 0; i < PDFTableConfig.Rows.Count; i++)
            {
                iTextSharp.text.pdf.PdfPCell aCell = new iTextSharp.text.pdf.PdfPCell();
                aCell.Colspan = (int)PDFTableConfig.Rows[i]["ColSpan"];
                aCell.Rowspan = (int)PDFTableConfig.Rows[i]["RowSpan"];

                aCell.BorderColor = GetCellBorderOrBackGroundColor(PDFTableConfig.Rows[i]["Border Color"].ToString());
                aCell.BackgroundColor = GetCellBorderOrBackGroundColor(PDFTableConfig.Rows[i]["BackGround Color"].ToString());
                aCell.HorizontalAlignment = GetTextAlign(PDFTableConfig.Rows[i]["Text Align"].ToString());

                string fontName = PDFTableConfig.Rows[i]["Font Name"].ToString();
                string fontEncoding = PDFTableConfig.Rows[i]["Font Encoding"].ToString();
                int fontSize = (int)PDFTableConfig.Rows[i]["FontSize"];

                int fontStyle = ReturnFontStyle(PDFTableConfig.Rows[i]["Font Style"].ToString());

                iTextSharp.text.BaseColor fontColor = GetCellBorderOrBackGroundColor(PDFTableConfig.Rows[i]["Font Color"].ToString());

                iTextSharp.text.Font currentFont = iTextSharp.text.FontFactory.GetFont(fontName,
                                                                fontEncoding,
                                                                fontSize,
                                                                fontStyle,
                                                                fontColor);

                aCell.Phrase = new iTextSharp.text.Phrase(PDFTableConfig.Rows[i]["ContentText"].ToString(), currentFont);

                aCell.Rotation = (int)PDFTableConfig.Rows[i]["TextRotation"];

                resultTable.AddCell(aCell);       
            }

            return resultTable;
        }


        private void createPDFButton_Click(object sender, EventArgs e)
        {
            int TableID = 0;
            DataTable mainPDFTableConfig = GetPDFConfigTable(TableID);

            PdfPTable mainPDFTable = null;

            if (mainPDFTableConfig != null && mainPDFTableConfig.Rows.Count > 0)
            {
                int tableColumnCount = GetTableColumnsCount(TableID);

                mainPDFTable = new PdfPTable(tableColumnCount);
                mainPDFTable.WidthPercentage = 100;

                for (int i = 0; i < mainPDFTableConfig.Rows.Count; i++)
                {
                    iTextSharp.text.pdf.PdfPCell aCell = new iTextSharp.text.pdf.PdfPCell();
                    aCell.Colspan = (int)mainPDFTableConfig.Rows[i]["ColSpan"];
                    aCell.Rowspan = (int)mainPDFTableConfig.Rows[i]["RowSpan"];

                    if (mainPDFTableConfig.Rows[i]["Content Type"].ToString().Equals("Table"))
                    {
                        int subtableID = -1;
                        int.TryParse(mainPDFTableConfig.Rows[i]["ContentText"].ToString(), out subtableID);

                        if (subtableID != -1)
                        {
                            PdfPTable subTable = CreatePdfPTable(subtableID);
                            if (subTable != null)
                            {
                                aCell.AddElement(subTable);
                                mainPDFTable.AddCell(aCell);
                            }
                        }
                    }
                    else
                    {
                        aCell.BorderColor = GetCellBorderOrBackGroundColor(mainPDFTableConfig.Rows[i]["Border Color"].ToString());
                        aCell.BackgroundColor = GetCellBorderOrBackGroundColor(mainPDFTableConfig.Rows[i]["BackGround Color"].ToString());
                        aCell.HorizontalAlignment = GetTextAlign(mainPDFTableConfig.Rows[i]["Text Align"].ToString());

                        string fontName = mainPDFTableConfig.Rows[i]["Font Name"].ToString();
                        string fontEncoding = mainPDFTableConfig.Rows[i]["Font Encoding"].ToString();
                        int fontSize = (int)mainPDFTableConfig.Rows[i]["FontSize"];

                        int fontStyle = ReturnFontStyle(mainPDFTableConfig.Rows[i]["Font Style"].ToString());

                        iTextSharp.text.BaseColor fontColor = GetCellBorderOrBackGroundColor(mainPDFTableConfig.Rows[i]["Font Color"].ToString());

                        iTextSharp.text.Font currentFont = iTextSharp.text.FontFactory.GetFont(fontName,
                                                                    fontEncoding,
                                                                    fontSize,
                                                                    fontStyle,
                                                                    fontColor);

                        aCell.Phrase = new iTextSharp.text.Phrase(mainPDFTableConfig.Rows[i]["ContentText"].ToString(), currentFont);


                        aCell.Rotation = (int)mainPDFTableConfig.Rows[i]["TextRotation"];

                        mainPDFTable.AddCell(aCell);
                    }
                }
            }

            if (mainPDFTable != null)
            {
                string payslipFilePath = "d:\\Payslip-Multitable.pdf";
                iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 9, 9, 9, 9);
                iTextSharp.text.pdf.PdfWriter pdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, new FileStream(payslipFilePath, FileMode.Create));
                pdfWriter.CompressionLevel = 9;
                pdfWriter.Open();
                pdfDocument.Open();
                pdfDocument.AddTitle("Payslip - multitable");

                pdfDocument.Add(mainPDFTable);



                pdfWriter.Flush();
                pdfDocument.Close();
                pdfWriter.Close();

                System.Diagnostics.Process.Start(payslipFilePath);
            }
        }        
    }
}
